<template>
  <div class="card-out-container prod-time-container">
    <CustomTable
      storeTableName="prodTimeInfoTable"
      rowKey="id"
      :loading="loading"
      bordered
      size="small"
      :dataSource="dataSource"
      :columns="columns"
      :pagination="false"
      :scroll="{ x: 1000, y: 'calc(100vh - 320px)' }"
      :resizeColumns="true"
      @columnsChange="columnsChange"
    >
      <template #operateLeft>
        <div class="operate-left">
          <a-button type="primary" @click="operateClick({ value: 1 })"
            >{{ $t('hangManage.allReceive') }}</a-button
          >
          <a-button ghost type="primary" @click="operateClick({ value: 3 })">{{ $t('hangManage.allLogin') }}</a-button>
          <a-button ghost type="primary" @click="operateClick({ value: 4 })">{{ $t('hangManage.allLoginOut') }}</a-button> 
        </div>
      </template>
      <template #bodyCell="{ scope }">
        <template v-if="scope.column.key === 'stationNo'">
          <div class="station-coloum-inner">
            <span
              v-if="
                scope.record.stationNo &&
                `${scope.record.stationNo}`.length <= 10
              "
              :class="{ 'text-red': !scope.record.staffNo }"
              :title="scope.record.stationNo"
              >{{ scope.record.hangerLineNo }} -
              {{ scope.record.stationNo }}</span
            >
            <a-tooltip v-else>
              <template #title>
                <span>{{ scope.record.stationNo }}</span>
              </template>
              <span
                :class="{ 'text-red': !scope.record.staffNo }"
                :title="scope.record.stationNo"
                >{{
                  scope.record.stationNo &&
                  `${scope.record.stationNo}`.split(0, 7) + "..."
                }}</span
              >
            </a-tooltip>
            <edit-outlined
              class="code-link"
              @click="editStation(scope.record)"
            />
          </div>
        </template>
        <template v-else-if="scope.column.key === 'role'">
          <span
            v-if="getText(roleColorList, scope.record.role, 'value') == '/'"
          ></span>
          <a-tag
            v-else
            :class="
              getFieldText(roleColorList, scope.record.role, 'value', 'color')
            "
          >
            {{ getText(roleColorList, scope.record.role, "value") }}
          </a-tag>
        </template>
        <template
          v-else-if="
            scope.column.key === 'staffNo' || scope.column.key === 'staffName'
          "
        >
          <span
            v-if="
              scope.record.staffName.length > 0 &&
              scope.record.staffNo.length > 0
            "
            >{{ scope.record.staffName }} ({{ scope.record.staffNo }})
          </span>
          <span
            v-else-if="
              scope.record.staffName.length > 0 &&
              scope.record.staffNo.length === 0
            "
            >{{ scope.record.staffName }}
          </span>
          <span
            v-else-if="
              scope.record.staffName.length === 0 &&
              scope.record.staffNo.length > 0
            "
            >({{ scope.record.staffNo }})
          </span>
          <span v-else>/</span>
        </template>
        <template v-else-if="scope.column.key === 'receiveCoatHanger'">
          <a-checkbox
            :checked="scope.record.receiveCoatHanger"
            @change="
              (value) =>
                receivecCoathanger(
                  value,
                  url.receivecCoathanger,
                  scope.record,
                  false
                )
            "
          />
        </template>
        <template v-else-if="scope.column.key === 'autoOutCloth'">
          <a-checkbox
            v-model:checked="scope.record.autoOutCloth"
            @change="
              (value) =>
                receiveOutClothes(value, url.allStrip, scope.record, false)
            "
          />
          <span
            v-if="scope.record.autoOutCloth && scope.record.autoOutClothSpeed"
          >
            ({{ scope.record.autoOutClothSpeed }})</span
          >
        </template>
        <template v-else-if="scope.column.key === 'hangerLineNo'">
          <a-checkbox
            @change="
              (value) =>
                receiveOutClothes(
                  value,
                  url.receivecCoathanger,
                  scope.record,
                  false
                )
            "
          ></a-checkbox>
        </template>
        <template v-else-if="scope.column.key === 'roadmap'">
          <span
            :class="scope.record.roadmap ? 'code-link' : ''"
            v-if="scope.record.role == '2'"
            @click="editRoadmap(scope.record)"
            >{{ scope.record.roadmap || $t('common.pleaseSelect') }}</span
          >
          <span v-else>{{ scope.record.roadmap || "" }}</span>
          <swap-outlined
            class="code-link ml-8 trans90"
            v-if="scope.record.role == '2'"
            @click="showRoadmap(scope.record)"
          />
        </template>
        <template v-else-if="scope.column.key === 'stationFull'">
          <a-tag color="error" v-if="scope.record.stationFull">{{ $t('sysManage.fullStation') }}</a-tag>
        </template>
        <template v-else-if="scope.column.key === 'masterTrackFull'">
          <a-tag color="error" v-if="scope.record.masterTrackFull">{{ $t('other.fullRail') }}</a-tag>
        </template>
        <template v-else-if="scope.column.key === 'onlineQty'">
          <span class="code-link" @click="showOnOrbitInfo(scope.record)">{{ scope.record.onlineQty }}</span>
        </template>
        <template v-else-if="scope.column.key === 'stationQty'">
          <a-row>
            <a-col :span="17">
              <a-progress
                :percent="getPercentInfo(scope.record, 'progress')"
                :strokeColor="getPercentInfo(scope.record)"
                :show-info="false"
              />
            </a-col>
            <a-col
              :span="7"
              class="code-link"
              @click="showHangerInfo(scope.record)"
              >{{ scope.record.stationQty }}</a-col
            >
          </a-row>
        </template>
      </template>
      <template #summary v-if="dataSource.length">
        <a-table-summary fixed>
          <a-table-summary-row class="text-right">
            <a-table-summary-cell
              v-for="item in columnsAry"
              :key="item.dataIndex"
              :index="item.dataIndex"
              :fixed="item.dataIndex == 'stationNo' ? 'left' : ''"
            >
              <div v-if="item.dataIndex == 'stationNo'" class="text-center"> {{$t('common.totals')}} </div>
              <span v-if="item.dataIndex == 'produceQty'">{{ totalTasks("produceQty") }}</span>
              <span v-if="item.dataIndex == 'reworkQty'">{{ totalTasks("reworkQty") }}</span>
              <span v-if="item.dataIndex == 'onlineQty'">{{ totalTasks("onlineQty") }}</span>
              <span v-if="item.dataIndex == 'stationQty'">{{ totalTasks("stationQty") }}</span>
            </a-table-summary-cell>
          </a-table-summary-row>
        </a-table-summary>
      </template>
    </CustomTable>
    <edit-station-modal ref="editStationModal" @ok="modalFormOk" />
    <roadmap-modal ref="roadmapModal" />
    <hanger-info-modal ref="hangerInfoModal" />
    <editRouteModal ref="editRouteModalRef" @ok="modalFormOk" />
    <on-orbit-info-modal ref="onOrbitInfoModal" />
    <EditOtherModal ref="editOtherModalRef" @ok="modalDesign"/>
  </div>
</template>

<script>
import { EditOutlined, SwapOutlined } from "@ant-design/icons-vue";
import { ListMixinPm } from "@/mixin/listMixinPm.js";
import EditStationModal from "./modules/editStationModal";
import RoadmapModal from "./modules/roadmapModal";
import HangerInfoModal from "./modules/hangerInfoModal.vue";
import EditOtherModal from "./modules/editOtherModal.vue";
import OnOrbitInfoModal from "./modules/onOrbitInfoModal.vue";
import editRouteModal from "@/views/makeManage/routeChart/modules/editRouteModal.vue";
import { listColumns, roleColorList } from "./modules/prodTimeConfig";
import { getFieldText, getText } from "@/utils";
import { cloneDeep, isEmpty } from "lodash";
import CustomTable from "@/components/commonTable/customTable.vue";
import { mapState } from "vuex";
// import { store } from '@/store'
import axios from "@/utils/request";
export default {
  name: "prodTimeInfo",
  mixins: [ListMixinPm],
  components: {
    EditStationModal,
    RoadmapModal,
    EditOutlined,
    HangerInfoModal,
    editRouteModal,
    SwapOutlined,
    CustomTable,
    OnOrbitInfoModal,
    EditOtherModal,
  },
  computed: {
    ...mapState({
      onlineRoadMap: (state) => state.normalData.onlineRoadMap,
      currentLine: (state) => state.setting.currentLine,
    }),
  },
  watch: {
    currentLine: {
      handler() {
        this.loadData();
      },
      deep: true,
      // immediate: true,
    },
  },
  data() {
    return {
      url: {
        list: "/api/hanger/hangerline-realtime/get",
        delete: "/api/system/post/delete",
        receivecAllCoathanger:
          "/api/hanger/hangerline-realtime/receive-coathanger",
        receivecCoathanger:
          "/api/hanger/hangerline-realtime/single-receive-coathanger",
        allOffline: "/api/hanger/hangerline-realtime/staff-offline",
        allLogin: "/api/hanger/hangerline-realtime/staff-online",
        autoCloth: "/api/hanger/hangerline-realtime/update-station-autoout",
        allStrip: "/api/hanger/hangerline-realtime/update-station-autoout",
      },
      dataSource: [],
      columns: listColumns,
      columnsAry: [],
      roleColorList,
      timer: null,
      showMore: true,
    };
  },
  methods: {
    modalDesign(){
      console.log(23)
    },
    totalTasks(numType) {
      let totalNo = this.dataSource.reduce((prev, next) => {
        return prev + (next[numType] || 0);
      }, 0);
      return totalNo;
    },
    getText,
    getFieldText,
    getQueryParams() {
      let param = cloneDeep(this.queryParam);
      param.hangerLineId = this.currentLine ? this.currentLine.id : null;
      return param || {};
    },
    async loadData() {
      let params = this.getQueryParams();
      // this.loading = true
      if (!params.hangerLineId) return;

      let res = await axios.postAction(this.url.list, params);
      if (res.success) {
        this.dataSource = res.data || [];
      }
    },
    getPercentInfo(record, type) {
      let percent =
        (record.stationQty / record.stationCapacity).toFixed(2) * 100;
      if (type == "progress") return percent;
      let color = "#3E8FF7";
      if (percent >= 60 && percent < 80) {
        color = "#FFA631";
      } else if (percent >= 80) {
        color = "#FB602D";
      }
      return color;
    },
    columnsChange(column) {
      this.columnsAry = column.filter((i) => i.visibility);
    },
    editRoadmap(record) {
      if (!record.roadmap) return;
      this.$refs.editRouteModalRef.open({
        moId: record.moId,
        routeId: record.roadmapId,
        isProdTime: true,
      });
    },
    showRoadmap(record) {
      this.$refs.roadmapModal.open(record);
    },
    editStation(record) {
      this.$refs.editStationModal.open(record);
    },
    // 站内衣架信息
    showHangerInfo(record) {
      // if (!["1", "3", "4", "5"].includes(record.role)) return;
      // if (!(["3", "4", "5"].includes(record.role) && record.stationQty)) return;
      if (!(this.currentLine && this.currentLine.id)) {
        this.$message.warning(this.$t('video.pleaseSelectWaterLine'));
      } else {
        this.$refs.hangerInfoModal.open(record);
      }
    },
    // 在轨衣架信息
    showOnOrbitInfo(record) {
      // if (!["1", "3", "4", "5"].includes(record.role)) return;
      // if (!(["3", "4", "5"].includes(record.role) && record.stationQty)) return;
      if (!(this.currentLine && this.currentLine.id)) {
        this.$message.warning(this.$t('video.pleaseSelectWaterLine'));
      } else {
        this.$refs.onOrbitInfoModal.open(record);
      }
    },
    receivecCoathanger(open, url, record, needConfirm = true) {
      if (!(this.currentLine && this.currentLine.id)) {
        this.$message.warning(this.$t('video.pleaseSelectWaterLine'));
      } else {
        let params = {
          hangerLineId: this.currentLine.id,
          receive: !isEmpty(open.target) ? open.target.checked : open,
          stationId: record ? record.stationId : null,
        };
        needConfirm
          ? this.confirmChangeStatus(
              url,
              params,
              `${this.$t('other.verify')}${record ? "" : this.$t('common.all')}${open ? this.$t('hangManage.receive') : this.$t('other.shutdown')}${this.$t('hangManage.hanger')}？`
            )
          : this.customChangeStatus(url, params);
      }
    },
    receiveOutClothes(open, url, record, needConfirm = true) {
      if (!(this.currentLine && this.currentLine.id)) {
        this.$message.warning(this.$t('video.pleaseSelectWaterLine'));
      } else {
        // console.log(open, url, record, needConfirm)
        // console.log(open.target.checked)
        let params = {
          autoOutCloth: open.target.checked,
          hangerLineId: record.hangerLineId,
          line: record.hangerLineNo,
          role: record.role,
          station: record.stationNo,
          stationId: record.stationId,
          stationCapacity: record.stationCapacity,
          autoOutClothSpeed: record.autoOutClothSpeed,
        };
        // console.log(record)
        // console.log(params)
        needConfirm
          ? this.confirmChangeStatus(
              url,
              params,
              `${this.$t('other.verify')}${record ? "" : this.$t('common.all')}${open ? this.$t('other.auto') : this.$t('other.manual')}${this.$t('other.undress')}？`
            )
          : this.customChangeStatus(url, params);
      }
    },
    operateClick(item, record) {
      console.log("🚀 ~!!!!! ~ item", item, record);
      switch (item.value) {
        case 1: // 全部接收衣架
          this.receivecCoathanger(true, this.url.receivecAllCoathanger);
          break;
        case 2: // 全部停收衣架
          this.receivecCoathanger(false, this.url.receivecAllCoathanger);
          break;
        case 3: // 登录全部员工
          if (!(this.currentLine && this.currentLine.id)) {
            this.$message.warning(this.$t('video.pleaseSelectWaterLine'));
          } else {
            this.confirmChangeStatus(
              this.url.allLogin,
              { id: this.currentLine.id },
              this.$t('other.sureLogAll')
            );
          }
          break;
        case 4: // 批量登出员工
          if (!(this.currentLine && this.currentLine.id)) {
            this.$message.warning(this.$t('video.pleaseSelectWaterLine'));
          } else {
            this.confirmChangeStatus(
              this.url.allOffline,
              { id: this.currentLine.id },
              this.$t('other.staffAllLogin')
            );
          }
          break;
        case 5: // 开启自动出衣
          if (!(this.currentLine && this.currentLine.id)) {
            this.$message.warning(this.$t('video.pleaseSelectWaterLine'));
          } else {
            this.confirmChangeStatus(
              this.url.allStrip,
              { id: this.currentLine.id },
              this.$t('other.sureOpenAuto')
            );
          }
          break;
        case 6: // 关闭自动出衣
          if (!(this.currentLine && this.currentLine.id)) {
            this.$message.warning(this.$t('video.pleaseSelectWaterLine'));
          } else {
            this.confirmChangeStatus(
              this.url.allStrip,
              { id: this.currentLine.id },
                this.$t('other.sureCloseAuto')+'?'
            );
          }
          break;
        case 8: // 更多
          this.$refs.editOtherModalRef.open()
          break;
        default:
          break;
      }
    },
  },
  beforeUnmount() {
    clearInterval(this.timer);
    this.timer = null;
  },
  unmounted() {
    clearInterval(this.timer);
    this.timer = null;
  },
  created() {
    this.loadData();
    console.log(this.$route.fullPath)
    this.timer = setInterval(() => {
      if (this.$route.fullPath === "/hangManage/prodTimeInfo") {
        this.loadData();
      }
    }, 3000);
  },
};
</script>